<template>
  <!-- 筛选产品list -->
  <div class="body">
    <Header @SearchBtn="SearchBtn" :menuIndex="menuIndex"></Header>
    <div class="cennterContent">
      <!-- 方案列表 -->
      <div class="solutionListBox filter">
        <div id="J_goodsList" class="goods-list-v2 gl-type-2 J-goods-list">
          <div class="title">Scheme</div>

          <div style="width: 100%; height: 588px">
            <pie
              v-if="schemeList && schemeList.length > 0"
              :PropData="schemeList"
              :index="'scheme8'"
            ></pie>
          </div>
        </div>
        <div id="J_goodsList" class="goods-list-v2 gl-type-2 J-goods-list">
          <div class="title">Solution</div>

          <commonChart
            :option="SolutionOption"
            v-if="SolutionOption"
            style="width: 100%; height: 588px"
          ></commonChart>
        </div>
        <div id="J_goodsList" class="goods-list-v2 gl-type-2 J-goods-list">
          <div class="title">BaseLineAndLessonLearn</div>
          <div class="flex">
            <!-- <div v-for="(item, index) in DepartmentInfo" :key="index" style="width:50%;">
              <div
                class="BaseLineAndLessonLearnBox"
                v-if="checkTheDeptName(BaseLineAndLessonLearnList,item.DeptName)&&checkTheDeptName(BaseLineAndLessonLearnList,item.DeptName).length>0"
              >
                <div class="name">{{ item.DeptName }}</div>
                <pie
                  :PropData="checkTheDeptName(BaseLineAndLessonLearnList,item.DeptName)"
                  style="width:100%;height:388px;"
                ></pie>
              </div>

            </div>-->
            <div
              v-for="(item, index) in BaseLineAndLessonLearnByGroupList"
              :key="index"
              style="width: 50%"
            >
              <div class="BaseLineAndLessonLearnBox">
                <div class="name">{{ item.DeptName }}</div>
                <!-- :PropData="checkTheDeptName(item,item)" -->

                <pie
                  :PropData="item.List"
                  v-if="item.List"
                  style="width: 100%; height: 388px"
                ></pie>
              </div>
            </div>
          </div>
        </div>
        <div id="J_goodsList" class="goods-list-v2 gl-type-2 J-goods-list">
          <div class="title">Innovation</div>

          <commonChart
            :option="InnovationOption"
            v-if="InnovationOption"
            style="width: 100%; height: 588px"
          ></commonChart>
        </div>

        <div class="flex topListBox">
          <div class="hotCase">
            <div class="title">Top5 Popular Case</div>
            <div class="rank-tab-content">
              <div
                class="rank-tab-content-item fore_rank-tab-content-0-0"
                v-for="(item, index) in SchemeTop5List"
                :key="index"
              >
                <div class="rank-icon fl">{{ index + 1 }}</div>
                <div class="fr">{{ item.ProjectName }}</div>
                <div class="hotNum">
                  <img
                    src="@/assets/img/index/hotNum.png"
                    class="hotNum-icon"
                  />
                  {{ item.quantity }}
                </div>
              </div>
            </div>
          </div>
          <div class="hotCase ml38">
            <div class="title">Top5 JABIL Coin</div>
            <div class="rank-tab-content">
              <div
                class="rank-tab-content-item fore_rank-tab-content-0-0"
                v-for="(item, index) in JabilComeTop5List"
                :key="index"
              >
                <div class="rank-icon fl">{{ index + 1 }}</div>
                <div class="fr">{{ item.ProjectName }}</div>
                <div class="hotNum">
                  <img src="@/assets/img/List/coin.png" class="hotNum-icon" />
                  {{ item.quantity }}
                </div>
              </div>
            </div>
          </div>
          <div class="hotCase">
            <div class="title">Top5 Innovation</div>
            <div class="rank-tab-content">
              <div
                class="rank-tab-content-item fore_rank-tab-content-0-0"
                v-for="(item, index) in InnovationTop5List"
                :key="index"
              >
                <div class="rank-icon fl">{{ index + 1 }}</div>
                <div class="fr">{{ item.ProjectName }}</div>
                <div class="hotNum">
                  <img
                    src="@/assets/img/index/hotNum.png"
                    class="hotNum-icon"
                  />
                  {{ item.quantity }}
                </div>
              </div>
            </div>
          </div>
          <div class="hotCase ml38">
            <div class="title">Top5 SupplierSolution</div>
            <div class="rank-tab-content">
              <div
                class="rank-tab-content-item fore_rank-tab-content-0-0"
                v-for="(item, index) in SupplierSolutionTop5List"
                :key="index"
              >
                <div class="rank-icon fl">{{ index + 1 }}</div>
                <div class="fr">{{ item.ProjectName }}</div>
                <div class="hotNum">
                  <img
                    src="@/assets/img/index/hotNum.png"
                    class="hotNum-icon"
                  />
                  {{ item.quantity }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style="margin: 38px 0">
          <div class="title">Login Statistics</div>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-statistic
                title="Number of logged in users"
                :value="LoginStaticsInfo.UserLoginTotal"
                style="margin-right: 50px"
              >
              </a-statistic>
            </a-col>
            <a-col :span="12">
              <a-statistic
                title="Number of online users"
                :value="LoginStaticsInfo.UserOnlineTotal"
                class="demo-class"
              >
              </a-statistic>
            </a-col>
          </a-row>
        </div>
        <div>
          <div class="title">
            LoginDetails
            <a-button @click="downLoadLoginFile(1)" style="margin: 38px"
              >DownloadLoginDeatails</a-button
            >
          </div>
          <a-table
            :data-source="LoginDetailList"
            :rowKey="(record, index) => index"
            :pagination="{
              total: LoginDetailsTotal,
              pageSize: LoginDetailPageSize,
              current: LoginDetailCurrent,
            }"
            @change="changePage"
            @showSizeChange="changePage"
          >
            <a-table-column key="#" title="#" data-index="#" />
            <a-table-column key="Name" title="Name" data-index="Name" />
            <a-table-column key="ID#" title="ID#" data-index="ID#" />
            <a-table-column
              key="Function"
              title="Function"
              data-index="Function"
            />
            <a-table-column
              key="Workcell"
              title="Workcell"
              data-index="Workcell"
            />
            <a-table-column
              key="Login status"
              title="Login status"
              data-index="Login status"
            />
          </a-table>
        </div>
        <div>
          <div class="title">
            LoginSummary
            <a-button @click="downLoadLoginFile(2)" style="margin: 38px"
              >DownloadLoginSummary</a-button
            >
          </div>
          <a-table
            :data-source="LoginSummaryList"
            :pagination="{
              total: LoginSummaryTotal,
              pageSize: LoginSummaryPageSize,
              current: LoginSummaryCurrent,
            }"
            @change="changeSummaryPage"
            @showSizeChange="changeSummaryPage"
            :rowKey="(record, index) => index"
          >
            <a-table-column
              key="Function"
              title="Function"
              data-index="Function"
            />
            <a-table-column
              key="Workcell"
              title="Workcell"
              data-index="Workcell"
            />
            <a-table-column
              key="Total HCs"
              title="Total HCs"
              data-index="Total HCs"
            />
            <a-table-column
              key="Login HCs"
              title="Login HCs"
              data-index="Login HCs"
            />
            <a-table-column
              key="Completed%"
              title="Completed%"
              data-index="Completed%"
            />
          </a-table>
        </div>
      </div>
    </div>
    <!-- <datav></datav> -->
  </div>
</template>
<script>
import Header from '@/components/layout/pureHeader'
import singleRing from '@/components/echarts/singleRing'
import datav from '@/components/datav/index.vue'
import pie from '@/components/echarts/pie'
import commonChart from '@/components/echarts/commonChart'
import userApi from '@/api/httpApi/user'

export default {
  data() {
    return {
      SetFilterList: [], //筛选条件集合

      isMoreCompany: false,
      isShowAllCity: false,
      SearchText: '',
      theModule: '',
      schemeList: [],
      totalCount: 0,
      listPageSize: 20,
      listCurrentPage: 1,
      menuIndex: 5,
      pdfUrl: '',
      DSloution: '',
      solutionList: [],
      BaseLineAndLessonLearnList: [],
      BaseLineAndLessonLearnCongfigList: [],
      InnovationList: [],
      InnovationTop5List: [],
      SchemeTop5List: [],
      SupplierSolutionTop5List: [],
      JabilComeTop5List: [],
      DepartmentInfo: [],
      testList: {
        data: [
          {
            name: '周口',
            value: 55,
          },
          {
            name: '南阳',
            value: 120,
          },
        ],
        unit: '',
        showValue: true,
      },
      InnovationOption: {},
      SolutionOption: {},
      BaseLineAndLessonLearnOption: {},
      BaseLineAndLessonLearnByGroupList: [],
      LoginDetailList: [],
      LoginSummaryList: [],
      LoginDetailsTotal: 0,
      LoginSummaryTotal: 0,
      LoginDetailPageSize: 10,
      LoginSummaryPageSize: 10,
      LoginDetailCurrent: 1,
      LoginSummaryCurrent: 1,
      LoginStaticsInfo: {},
    }
  },
  components: {
    Header,
    singleRing,
    datav,
    pie,
    commonChart,
  },
  watch: {},
  created() {
    if (this.$route.query.index) {
      this.menuIndex = this.$route.query.index
    }
    this.getDeptInfo()
    this.getAllSchemeInfo()
    this.$forceUpdate()
    this.getLoginInfoList()
    this.getLoginStatics()
  },
  mounted() {},

  methods: {
    getLoginStatics() {
      const that = this
      userApi.getLogInStatistics().then((result) => {
        console.log(result.data)
        that.LoginStaticsInfo = result.data[0]
      })
    },
    changeSummaryPage(a, b) {
      // console.log(a, b, c)
      let pageInfo = a
      this.LoginSummaryPageSize = pageInfo.pageSize
      this.LoginSummaryCurrent = pageInfo.current
      this.getLoginInfoList(2)
    },
    changePage(a, b, c) {
      // console.log(a, b, c)
      let pageInfo = a
      this.LoginDetailPageSize = pageInfo.pageSize
      this.LoginDetailCurrent = pageInfo.current
      this.getLoginInfoList(1)
    },
    downLoadLoginFile(type) {
      userApi.downloadLoginFile(type).then((result) => {
        // console.log(result, '登录文件')
        if (result.data.xls) {
          if (type == 1) {
            this.$message.success(
              'The login details file was exported successfully'
            )
          } else {
            this.$message.success(
              'The login summary file was exported successfully'
            )
          }
          window.open(result.data.xls)
        }
      })
    },
    compare(property) {
      return function (a, b) {
        let value1 = a[property].replace('%', '')
        let value2 = b[property].replace('%', '')
        return Number(value1) - Number(value2)
      }
    },

    getLoginInfoList(type) {
      let LoginDetailData = {
        currentPage: this.LoginDetailCurrent,
        limit: this.LoginDetailPageSize,
      }
      let LoginSummaryData = {
        currentPage: this.LoginSummaryCurrent,
        limit: this.LoginSummaryPageSize,
      }
      if (type == 1) {
        userApi.getUserLoginDetails(LoginDetailData).then((result) => {
          // console.log('登录详情', result)
          this.LoginDetailList = result.data ? result.data : []
          this.LoginDetailsTotal = result.count
        })
      } else if (type == 2) {
        userApi.getUserLoginSummaey(LoginSummaryData).then((result) => {
          this.LoginSummaryList = result.data ? result.data : []
          console.log(
            '排序',
            this.LoginSummaryList.sort(this.compare('Completed%'))
          )
          this.LoginSummaryList = this.LoginSummaryList.sort(
            this.compare('Completed%')
          )
          this.LoginSummaryTotal = result.count
        })
      } else {
        userApi.getUserLoginDetails(LoginDetailData).then((result) => {
          // console.log('登录详情', result)
          this.LoginDetailList = result.data ? result.data : []
          this.LoginDetailsTotal = result.count
        })
        userApi.getUserLoginSummaey(LoginSummaryData).then((result) => {
          this.LoginSummaryList = result.data ? result.data : []
          console.log(
            '排序',
            this.LoginSummaryList.sort(this.compare('Completed%'))
          )
          this.LoginSummaryList = this.LoginSummaryList.sort(
            this.compare('Completed%')
          )
          this.LoginSummaryTotal = result.count
        })
      }
    },
    checkTheDeptName(list, name) {
      // console.log('list,name :>> ', list, name)
      let res = list.filter((item) => {
        // console.log('item :>> ', item)
        return item.DeptName == name
      })
      // console.log('res :>> ', res)
      return res
    },
    delFliter(index) {
      this.SetFilterList.splice(index, 1)
    },
    // 数组对象去重
    deWeight(arr) {
      for (var i = 0; i < arr.length - 1; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i].name == arr[j].name) {
            arr.splice(j, 1)
            //因为数组长度减小1，所以直接 j++ 会漏掉一个元素，所以要 j--
            j--
          }
        }
      }
      return arr
    },

    paginationChange(page, pageSize) {
      // console.log(page, pageSize)
      this.listCurrentPage = page
      this.listPageSize = pageSize
      this.getAllSchemeInfo()
    },
    toSchemePage(item) {
      // console.log('item :>> ', item)
      let data = JSON.stringify(item)
      //生成pdf 并打开预览
      if (item.PdfFile) {
        window.open(item.PdfFile)
      } else {
        this.$message.warning('PDF is not uploaded for this scenario')
      }
    },
    errorImg(event) {
      this.$pk.errorImg(event)
    },
    SearchBtn(e) {
      // console.log('e :>> ', e)
      this.SearchText = e
      this.getAllSchemeInfo()
    },
    showAllProject(type) {
      if (type === 'company') {
        this.isMoreCompany = !this.isMoreCompany
      } else if (type === 'city') {
        this.isShowAllCity = !this.isShowAllCity
      }
    },
    getSearchInfo(e) {
      // console.log('搜索内容', e)
      if (e) {
        this.SearchText = e[0]
        this.theModule = e[1]
      }
    },
    getAllSchemeInfo() {
      const that = this
      const a = {
        method: 'Statistics_Que',
        userId: window.userId || 1,
        sign: '1',
        currentPage: this.listCurrentPage,
        limit: this.listPageSize,
        language: window.language || 1,
        datas: {},
      }
      this.$post(a).then((result) => {
        console.log('result.data :>> ', result.data)
        this.schemeList = []
        this.solutionList = []
        this.BaseLineAndLessonLearnList = []
        this.BaseLineAndLessonLearnCongfigList = []
        this.InnovationOption = {}

        result.data.forEach((item) => {
          let type = item.ProjectType
          let obj = {}
          obj.name = item.ProjectName
          obj.value = item.quantity
          obj.DeptName = item.DeptName

          switch (type) {
            case 'Scheme':
              that.schemeList.push(obj)
              break
            case 'Solution':
              that.solutionList.push(item)
              break
            case 'BaseLineAndLessonLearn':
              if (item.DeptName) {
                that.BaseLineAndLessonLearnList.push(obj)
              }
              break
            case 'Innovation':
              if (item.DeptName) {
                that.InnovationList.push(item)
              }
              break
            case 'SchemeTop5':
              that.SchemeTop5List.push(item)

              break
            case 'SupplierSolutionTop5':
              that.SupplierSolutionTop5List.push(item)
              break
            case 'InnovationTop5':
              that.InnovationTop5List.push(item)
              break
            case 'Innovation':
              that.InnovationList.push(item)

              break
            case 'JabilComeTop5':
              that.JabilComeTop5List.push(item)
              break
          }
        })

        this.totalCount = result.count
        // console.log(
        //   'this.BaseLineAndLessonLearnList :>> ',
        //   this.BaseLineAndLessonLearnList
        // )
        let newArr = []
        for (let i = 0; i < this.DepartmentInfo.length; i++) {
          let obj = {}
          obj.data = []
          obj.unit = ''
          for (let j = 0; j < this.BaseLineAndLessonLearnList.length; j++) {
            if (
              this.DepartmentInfo[i].DeptName ==
              this.BaseLineAndLessonLearnList[j].DeptName
            ) {
              newArr.push(this.BaseLineAndLessonLearnList[j])
              let o = {}
              o.name = this.BaseLineAndLessonLearnList[j].ProjectName
              o.value = this.BaseLineAndLessonLearnList[j].quantity
              o.kk = this.BaseLineAndLessonLearnList[j].DeptName
              obj.data.push(o)
              obj.data = Array.from(new Set(obj.data))
            }
          }
          this.DepartmentInfo[i].config = obj

          this.$forceUpdate()
          // console.log('obj :>> ', obj)
        }
        that.makeInnovationData()
        that.makeSolutionData()
        that.makeBaseLineOption()
        that.BaseLineAndLessonLearnList = Array.from(
          new Set(this.BaseLineAndLessonLearnList)
        )
        let dataArr = []
        this.BaseLineAndLessonLearnList.map((mapItem) => {
          if (dataArr.length == 0) {
            dataArr.push({ DeptName: mapItem.DeptName, List: [mapItem] })
          } else {
            let res = dataArr.some((item) => {
              //判断相同日期，有就添加到当前项
              if (item.DeptName == mapItem.DeptName) {
                item.List.push(mapItem)
                return true
              }
            })
            if (!res) {
              //如果没找相同日期添加一个新对象
              dataArr.push({ DeptName: mapItem.DeptName, List: [mapItem] })
            }
          }
        })
        this.BaseLineAndLessonLearnByGroupList = dataArr

        // console.log('分组', dataArr)
      })
    },
    makeSolutionData() {
      let InnovationData = []
      let legendNameList = []
      this.solutionList.map((item) => {
        // console.log('item :>> ', item)
        let obj = {}
        obj.name = item.DeptName
        obj.value = item.quantity
        if (obj.name) {
          InnovationData.push(obj)
          legendNameList.push(obj.name)
        }
      })
      // console.log('legendNameList :>> ', legendNameList)
      this.SolutionOption = {
        title: {
          text: 'Innovation Statistics',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: legendNameList,
        },
        series: [
          {
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            data: InnovationData.length >= 0 ? InnovationData : [],
            emphasis: {
              label: {
                show: true,
                fontSize: '30',
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
          },
        ],
      }
      this.$forceUpdate()
    },
    async makeInnovationData() {
      let InnovationData = []
      let legendNameList = []
      this.InnovationList.map((item) => {
        // console.log('item :>> ', item)
        let obj = {}
        obj.name = item.DeptName
        obj.value = item.quantity
        InnovationData.push(obj)
        legendNameList.push(obj.name)
      })
      // console.log('legendNameList :>> ', legendNameList)
      this.InnovationOption = {
        title: {
          text: 'Innovation Statistics',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: legendNameList,
        },
        series: [
          {
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            data: InnovationData.length >= 0 ? InnovationData : [],
            emphasis: {
              label: {
                show: true,
                fontSize: '30',
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
          },
        ],
      }
      this.$forceUpdate()
    },
    makeBaseLineOption() {
      let InnovationData = []
      let legendNameList = []

      // console.log('legendNameList :>> ', legendNameList)
      this.BaseLineAndLessonLearnOption = {
        // title: {
        //   text: 'Scheme Statistics',
        //   left: 'center',
        // },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: legendNameList.length >= 0 ? legendNameList : [],
        },
        series: [
          {
            name: '方案统计',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: InnovationData.length >= 0 ? InnovationData : [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      }
      this.$forceUpdate()
    },
    getDeptInfo() {
      const a = {
        method: 'SysDept_Que',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        datas: {},
      }
      this.$post(a).then((result) => {
        this.DepartmentInfo = result.data.length > 0 ? result.data : []
      })
    },
    test() {
      var arr = [1, 5, 6, 0, 7, 3, 0, 5, 9, 5, 5]
      let kk = []
      function unique(arr) {
        for (var i = 0, len = arr.length; i < len; i++) {
          for (var j = i + 1, len = arr.length; j < len; j++) {
            if (arr[i] === arr[j]) {
              kk.push(arr[i])
            }
          }
        }
        return kk
      }
      // console.log(unique(arr)) //  1, 5, 6, 0, 7, 3, 9
    },
  },
}
</script>
<style lang="less" scoped>
@import url('css/Statistics.less');
</style>
